<template>
  <div>
    <div
      style="
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 20px;
      "
    >
      <div>选择日期：</div>
      <el-date-picker
        v-model="defectMonth"
        size="small"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="changeMonth('change')"
      >
      </el-date-picker>
    </div>
    <div class="content">
      <el-card class="box-card">
        <div class="boxTop">
          <div class="boxTitle">缺陷专业</div>
          <div class="boxSelect"></div>
        </div>
        <div class="defectContent">
          <verticalBar
            :id="'defectMajorId'"
            :type="'cockpit'"
            :option="defectMajorOption"
          ></verticalBar>
        </div>
      </el-card>
      <el-card class="box-card">
        <div class="boxTop">
          <div class="boxTitle">缺陷类型</div>
          <div class="boxSelect"></div>
        </div>
        <div class="defectContent">
          <verticalBar
            :id="'defectLevelId'"
            :type="'cockpit'"
            :option="defectLevelOption"
          ></verticalBar>
        </div>
      </el-card>
      <el-card class="box-card">
        <div class="boxTop">
          <div class="boxTitle">缺陷类型</div>
          <div class="boxSelect"></div>
        </div>
        <div class="defectContent">
          <verticalBar
            :id="'defectDeptId'"
            :type="'cockpit'"
            :option="defectDeptOption"
          ></verticalBar>
        </div>
      </el-card>
      <el-card class="box-card">
        <div class="boxTop">
          <div class="boxTitle">缺陷来源</div>
          <div class="boxSelect"></div>
        </div>
        <div class="defectContent">
          <verticalBar
            :id="'defectSourceId'"
            :type="'cockpit'"
            :option="defectSourceOption"
          ></verticalBar>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getDefectChatDate } from "@/api/orderManagement/defectDensityStatistic.js";
import verticalBar from "@/components/echart/verticalBar";
export default {
  components: {
    verticalBar,
  },
  data() {
    return {
      // 月份
      defectMonth: [],

      // 缺陷专业列表
      defectMajorList: [],
      defectMajorTotal: 0,
      defectMajorOption: {},

      // 缺陷等级
      defectLevelList: [],
      defectLevelTotal: 0,
      defectLevelOption: {},

      // 缺陷部门
      defectDeptList: [],
      defectDeptTotal: 0,
      defectDeptOption: {},

      // 缺陷来源
      defectSourceList: [],
      defectSourceTotal: 0,
      defectSourceOption: {},

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    init() {
      this.defectMonth = this.getCurrentMonthFirstAndLastDay(
        this.$utils.getCurrentDate(1)
      );
      this.changeMonth();
    },
    // 格式化日期（yyyy-MM-dd）
    formatDate(inputDate, type = "full") {
      const date = new Date(inputDate);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");

      if (type === "full") return `${year}-${month}-${day}`;
      if (type === "month-day") return `${month}-${day}`;
      if (type === "day") return `${day}`;
      if (type === "hour-minute") return `${hours}:${minutes}`;
    },
    // 改变缺陷专业月份
    changeMonth(type = "") {
      let changeDate;
      // 获取当前年月日
      if (type == "change") {
        changeDate = [
          this.formatDate(this.defectMonth[0]),
          this.formatDate(this.defectMonth[1]),
        ];
      } else {
        changeDate = this.getCurrentMonthFirstAndLastDay(
          this.$utils.getCurrentDate(1)
        );
      }
      let params = {
        startTime: changeDate[0],
        endTime: changeDate[1],
      };
      getDefectChatDate(params).then((res) => {
        try {
          if (res.code == 200) {
            // 总数清空
            this.defectMajorTotal = 0;
            this.defectMajorTotal = res.data.major.reduce((prev, curr) => {
              return prev + curr.count;
            }, this.defectMajorTotal);
            this.defectMajorList = res.data.major.map((item) => {
              return {
                name: item.value,
                value: item.count,
                percentage: item.percent.substring(0, 5) + "%",
              };
            });
            this.getDefectMajorOption(this.defectMajorList);

            this.defectLevelTotal = 0;
            this.defectLevelTotal = res.data.level.reduce((prev, curr) => {
              return prev + curr.count;
            }, this.defectLevelTotal);
            this.defectLevelList = res.data.level.map((item) => {
              return {
                name: item.value,
                value: item.count,
                percentage: item.percent.substring(0, 5) + "%",
              };
            });
            this.getDefectLevelOption(this.defectLevelList);

            this.defectDeptTotal = 0;
            this.defectDeptTotal = res.data.dept.reduce((prev, curr) => {
              return prev + curr.count;
            }, this.defectDeptTotal);
            this.defectDeptList = res.data.dept.map((item) => {
              return {
                name: item.value,
                value: item.count,
                percentage: item.percent.substring(0, 5) + "%",
              };
            });
            this.getDefectDeptOption(this.defectDeptList);

            this.defectSourceTotal = 0;
            this.defectSourceTotal = res.data.source.reduce((prev, curr) => {
              return prev + curr.count;
            }, this.defectSourceTotal);
            this.defectSourceList = res.data.source.map((item) => {
              return {
                name: item.value,
                value: item.count,
                percentage: item.percent.substring(0, 5) + "%",
              };
            });
            this.getDefectSourceOption(this.defectSourceList);
          } else {
            throw new Error("getDefectChatDate服务响应code ≠ 200");
          }
        } catch (error) {
          console.error(error);
        }
      });
    },
    getDefectMajorOption(data) {
      const colors = [
        "#00468E",
        "#0D60B4",
        "#0083CC",
        "#18AAE3",
        "#00CDE2",
        "#22BB5F",
        "#00ff80",
        " #99ffcc",
      ];
      let optionData = data;
      let option = {
        color: colors,
        tooltip: {
          trigger: "item",
          // formatter: "{b}<br/>数量 {c} 个<br/>占比 {d}%",
          formatter: function (params) {
            let htmlStr = "";
            htmlStr +=
              "<div>" +
              "<span style='display:inline-block;margin-right:2px;width:10px;height:10px;background-color:" +
              params.color +
              "'></span>" +
              "<span style='display: inline-block; margin: 0 6px;font-size: 16px; font-family: Source Han Sans CN; font-weight: 600;color: #666;'>" +
              params.data.name +
              "</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 数量：" +
              params.data.value +
              "个</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 占比：" +
              params.data.percentage +
              "</span>" +
              "</div>";
            return htmlStr;
          },
          borderColor: "#fff",
          backgroundColor: "rgba(255,255,255,0.8)",
          textStyle: {
            //提示框内文字样式的设置
            fontSize: 14,
            fontFamily: "Source Han Sans CN",
            fontWeight: 400,
            color: "#666",
            align: "left",
          },
        },
        legend: {
          icon: "roundRect",
          itemWidth: 10, //图标宽
          itemHeight: 10, //图标高
          type: "scroll",
          orient: "vertical",
          selectedMode: false,
          formatter: function (name) {
            var target;
            for (var i = 0, l = optionData.length; i < l; i++) {
              if (optionData[i].name == name) {
                target = optionData[i].percentage;
              }
            }
            return `{one|${name}}  {two|${target}}`;
          },
          right: 20,
          top: 20,
          textStyle: {
            color: "#666",
            align: "left",
            rich: {
              one: {
                width: 100,
              },
              two: {
                width: 35,
                color: "#333",
                fontWeight: "bolder",
              },
            },
          },
        },
        series: [
          {
            right: 180,
            type: "pie",
            radius: ["70%", "90%"],
            // radius: ["80%", "100%"],
            avoidLabelOverlap: false,
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
              borderJoin: "round",
            },
            label: {
              //饼图中间插入文字
              show: true,
              position: "center", //居中
              formatter:
                "{value|" +
                this.defectMajorTotal +
                "}" +
                "\n\r" +
                "{total|专业缺陷数量（个）}",
              rich: {
                value: {
                  //value格式
                  fontSize: 24,
                  fontFamily: "PingFangSC-Semibold, sans-serif",
                  color: "#182F41",
                  lineHeight: 40,
                  fontWeight: 600,
                  padding: [-2, 0, 0, 0],
                },
                total: {
                  //总人数格式
                  fontFamily: "PingFangSC-Regular, sans-serif",
                  fontSize: 12,
                  color: "#7B8997",
                  lineHeight: 16,
                },
              },
            },
            labelLine: {
              show: false,
            },
            data: optionData,
          },
        ],
      };
      this.defectMajorOption = option;
    },
    getDefectLevelOption(data) {
      const colors = [
        "#EF4C4C",
        "#EA7550",
        "#FAA224",
        "#FFB357",
        "#FFD176",
        "#FFDF57",
        "#ffd699",
        "#ffaa80",
        "#ff884d",
        "#ffa64d",
      ];
      let optionData = data;
      let option = {
        color: colors,
        tooltip: {
          trigger: "item",
          // formatter: "{b}<br/>数量 {c} 个<br/>占比 {d}%",
          formatter: function (params) {
            let htmlStr = "";
            htmlStr +=
              "<div>" +
              "<span style='display:inline-block;margin-right:2px;width:10px;height:10px;background-color:" +
              params.color +
              "'></span>" +
              "<span style='display: inline-block; margin: 0 6px;font-size: 16px; font-family: Source Han Sans CN; font-weight: 600;color: #666;'>" +
              params.data.name +
              "</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 数量：" +
              params.data.value +
              "个</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 占比：" +
              params.data.percentage +
              "</span>" +
              "</div>";
            return htmlStr;
          },
          borderColor: "#fff",
          backgroundColor: "rgba(255,255,255,0.8)",
          textStyle: {
            //提示框内文字样式的设置
            fontSize: 14,
            fontFamily: "Source Han Sans CN",
            fontWeight: 400,
            color: "#666",
            align: "left",
          },
        },
        legend: {
          icon: "roundRect",
          itemWidth: 10, //图标宽
          itemHeight: 10, //图标高
          type: "scroll",
          orient: "vertical",
          selectedMode: false,
          formatter: function (name) {
            var target;
            for (var i = 0, l = optionData.length; i < l; i++) {
              if (optionData[i].name == name) {
                target = optionData[i].percentage;
              }
            }
            return `{one|${name}}  {two|${target}}`;
          },
          right: 20,
          top: 20,
          textStyle: {
            color: "#666",
            align: "left",
            rich: {
              one: {
                width: 100,
              },
              two: {
                width: 35,
                color: "#333",
                fontWeight: "bolder",
              },
            },
          },
        },
        series: [
          {
            right: 180,
            type: "pie",
            radius: ["70%", "90%"],
            // radius: ["80%", "100%"],
            avoidLabelOverlap: false,
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
              borderJoin: "round",
            },
            label: {
              //饼图中间插入文字
              show: true,
              position: "center", //居中
              formatter:
                "{value|" +
                this.defectLevelTotal +
                "}" +
                "\n\r" +
                "{total|等级缺陷数量（个）}",
              rich: {
                value: {
                  //value格式
                  fontSize: 24,
                  fontFamily: "PingFangSC-Semibold, sans-serif",
                  color: "#182F41",
                  lineHeight: 40,
                  fontWeight: 600,
                  padding: [-2, 0, 0, 0],
                },
                total: {
                  //总人数格式
                  fontFamily: "PingFangSC-Regular, sans-serif",
                  fontSize: 12,
                  color: "#7B8997",
                  lineHeight: 16,
                },
              },
            },
            labelLine: {
              show: false,
            },
            data: optionData,
          },
        ],
      };
      this.defectLevelOption = option;
    },
    getDefectDeptOption(data) {
      const colors = [
        "#5b7ad7",
        "#9fe080",
        "#fedb5f",
        "#f86c6c",
        "#73c0de",
        "#FFDF57",
        "#ffd699",
        "#ffaa80",
        "#ff884d",
        "#ffa64d",
      ];
      let optionData = data;
      let option = {
        color: colors,
        tooltip: {
          trigger: "item",
          // formatter: "{b}<br/>数量 {c} 个<br/>占比 {d}%",
          formatter: function (params) {
            let htmlStr = "";
            htmlStr +=
              "<div>" +
              "<span style='display:inline-block;margin-right:2px;width:10px;height:10px;background-color:" +
              params.color +
              "'></span>" +
              "<span style='display: inline-block; margin: 0 6px;font-size: 16px; font-family: Source Han Sans CN; font-weight: 600;color: #666;'>" +
              params.data.name +
              "</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 数量：" +
              params.data.value +
              "个</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 占比：" +
              params.data.percentage +
              "</span>" +
              "</div>";
            return htmlStr;
          },
          borderColor: "#fff",
          backgroundColor: "rgba(255,255,255,0.8)",
          textStyle: {
            //提示框内文字样式的设置
            fontSize: 14,
            fontFamily: "Source Han Sans CN",
            fontWeight: 400,
            color: "#666",
            align: "left",
          },
        },
        legend: {
          icon: "roundRect",
          itemWidth: 10, //图标宽
          itemHeight: 10, //图标高
          type: "scroll",
          orient: "vertical",
          selectedMode: false,
          formatter: function (name) {
            var target;
            for (var i = 0, l = optionData.length; i < l; i++) {
              if (optionData[i].name == name) {
                target = optionData[i].percentage;
              }
            }
            return `{one|${name}}  {two|${target}}`;
          },
          right: 20,
          top: 20,
          textStyle: {
            color: "#666",
            align: "left",
            rich: {
              one: {
                width: 100,
              },
              two: {
                width: 35,
                color: "#333",
                fontWeight: "bolder",
              },
            },
          },
        },
        series: [
          {
            right: 180,
            type: "pie",
            radius: ["70%", "90%"],
            // radius: ["80%", "100%"],
            avoidLabelOverlap: false,
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
              borderJoin: "round",
            },
            label: {
              //饼图中间插入文字
              show: true,
              position: "center", //居中
              formatter:
                "{value|" +
                this.defectDeptTotal +
                "}" +
                "\n\r" +
                "{total|部门缺陷数量（个）}",
              rich: {
                value: {
                  //value格式
                  fontSize: 24,
                  fontFamily: "PingFangSC-Semibold, sans-serif",
                  color: "#182F41",
                  lineHeight: 40,
                  fontWeight: 600,
                  padding: [-2, 0, 0, 0],
                },
                total: {
                  //总人数格式
                  fontFamily: "PingFangSC-Regular, sans-serif",
                  fontSize: 12,
                  color: "#7B8997",
                  lineHeight: 16,
                },
              },
            },
            labelLine: {
              show: false,
            },
            data: optionData,
          },
        ],
      };
      this.defectDeptOption = option;
    },
    getDefectSourceOption(data) {
      const colors = [
        "#ff915a",
        "#a969c6",
        "#ff88e0",
        "#5470c6",
        "#91cc75",
        "#3fb17c",
        "#ffd699",
        "#ffaa80",
        "#ff884d",
        "#ffa64d",
      ];
      let optionData = data;
      let option = {
        color: colors,
        tooltip: {
          trigger: "item",
          // formatter: "{b}<br/>数量 {c} 个<br/>占比 {d}%",
          formatter: function (params) {
            let htmlStr = "";
            htmlStr +=
              "<div>" +
              "<span style='display:inline-block;margin-right:2px;width:10px;height:10px;background-color:" +
              params.color +
              "'></span>" +
              "<span style='display: inline-block; margin: 0 6px;font-size: 16px; font-family: Source Han Sans CN; font-weight: 600;color: #666;'>" +
              params.data.name +
              "</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 数量：" +
              params.data.value +
              "个</span><br/>" +
              "<span style='display:inline-block;margin-right:4px;width:10px;height:10px;'></span>" +
              "<span style='color: #666;font-size: 14px;font-family: Source Han Sans CN; font-weight: 400;'> 占比：" +
              params.data.percentage +
              "</span>" +
              "</div>";
            return htmlStr;
          },
          borderColor: "#fff",
          backgroundColor: "rgba(255,255,255,0.8)",
          textStyle: {
            //提示框内文字样式的设置
            fontSize: 14,
            fontFamily: "Source Han Sans CN",
            fontWeight: 400,
            color: "#666",
            align: "left",
          },
        },
        legend: {
          icon: "roundRect",
          itemWidth: 10, //图标宽
          itemHeight: 10, //图标高
          type: "scroll",
          orient: "vertical",
          selectedMode: false,
          formatter: function (name) {
            var target;
            for (var i = 0, l = optionData.length; i < l; i++) {
              if (optionData[i].name == name) {
                target = optionData[i].percentage;
              }
            }
            return `{one|${name}}  {two|${target}}`;
          },
          right: 20,
          top: 20,
          textStyle: {
            color: "#666",
            align: "left",
            rich: {
              one: {
                width: 100,
              },
              two: {
                width: 35,
                color: "#333",
                fontWeight: "bolder",
              },
            },
          },
        },
        series: [
          {
            right: 180,
            type: "pie",
            radius: ["70%", "90%"],
            // radius: ["80%", "100%"],
            avoidLabelOverlap: false,
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
              borderJoin: "round",
            },
            label: {
              //饼图中间插入文字
              show: true,
              position: "center", //居中
              formatter:
                "{value|" +
                this.defectSourceTotal +
                "}" +
                "\n\r" +
                "{total|来源缺陷数量（个）}",
              rich: {
                value: {
                  //value格式
                  fontSize: 24,
                  fontFamily: "PingFangSC-Semibold, sans-serif",
                  color: "#182F41",
                  lineHeight: 40,
                  fontWeight: 600,
                  padding: [-2, 0, 0, 0],
                },
                total: {
                  //总人数格式
                  fontFamily: "PingFangSC-Regular, sans-serif",
                  fontSize: 12,
                  color: "#7B8997",
                  lineHeight: 16,
                },
              },
            },
            labelLine: {
              show: false,
            },
            data: optionData,
          },
        ],
      };
      this.defectSourceOption = option;
    },
    // 获取当前时间所处月份的第一天和最后一天
    getCurrentMonthFirstAndLastDay(date) {
      const year = date.substr(0, 4);
      const month = date.substr(5, 2);
      return [
        `${year}-${month}-01`,
        `${year}-${month}-${new Date(year, month, 0).getDate()}`,
      ];
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="less" scoped>
.defectContent {
  height: 200px;
}
.content {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .box-card {
    width: calc(50% - 20px);
    min-width: 300px;
    flex-shrink: 0;
    margin: 10px;

    .boxTop {
      display: flex;
      justify-content: space-between;

      .boxTitle {
        line-height: 32px;
        margin-left: 10px;
        font-size: 18px;
        font-weight: 500;
        color: #333333;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        text-align: left;

        &:before {
          margin-right: 10px;
          width: 4px;
          height: 18px;
          position: relative;
          top: 2px;
          background-color: #0d60b4;
          display: inline-block;
          content: "";
        }
      }

      .boxSelect {
        display: flex;
        .otherInfo {
          margin-right: 10px;
          /deep/ .el-input__inner {
            width: 114px;
          }
          /deep/ .el-scrollbar__wrap {
            overflow: scroll;
            height: 170px;
          }
        }
        .monthTime {
          margin-right: 10px;
          /deep/ .el-date-editor.el-input {
            width: 114px;
          }
        }
      }
    }
  }

  .text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }
}

/deep/.el-card__body {
  padding: 8px;
}
</style>
